package tvp.ltdd.fake_call_sms.activity;

import java.util.Calendar;

import tvp.ltdd.fake_call_sms.R;
import tvp.ltdd.fake_call_sms.helper.CallLogHelper;
import tvp.ltdd.fake_call_sms.receiver.CallReceiver;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

public class FragmentCall extends Fragment implements OnClickListener {
	private Button btnContact, btnRing, btnSave, btnCallTimer, btnSpeak;
	private ImageView imageViewContact;
	private EditText etName, etNumber;
	private TextView textView1;
	private ToggleButton tbPrivate, tbVibrate;
	private final int PICK = 1;
	private final int RING = 2;
	private final int TIME_DIALOG = 3;
	private final int DURATION_DIALOG = 4;
	private final Calendar c = Calendar.getInstance();
	private View rootView;
	private String ringTonePath;
	private String name;
	private int type;
	private int duration = 0;
	private RadioGroup group;
	private RadioButton button;
	private String ringtone;
	private long time = 0, date;
	private int hour;
	private int minute;
	private int current_hour;
	private int current_minute;
	private boolean vibrate = true;
	private String phoneId = "0";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		rootView = inflater.inflate(R.layout.call, container, false);

		btnCallTimer = (Button) rootView.findViewById(R.id.btnTimer);
		btnContact = (Button) rootView.findViewById(R.id.btnContact);
		btnRing = (Button) rootView.findViewById(R.id.btnRing);
		btnSpeak = (Button) rootView.findViewById(R.id.btnSpeak);
		btnSave = (Button) rootView.findViewById(R.id.btnSave);
		textView1 = (TextView) rootView.findViewById(R.id.tvNumber);
		etName = (EditText) rootView.findViewById(R.id.etName);
		etNumber = (EditText) rootView.findViewById(R.id.etNumber);
		group = (RadioGroup) rootView.findViewById(R.id.groupCall);
		tbPrivate = (ToggleButton) rootView.findViewById(R.id.tbPrivate);
		tbVibrate = (ToggleButton) rootView.findViewById(R.id.tbVibrate);
		imageViewContact = (ImageView) rootView
				.findViewById(R.id.imageViewContact);
		tbPrivate.setOnClickListener(this);
		tbVibrate.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		btnContact.setOnClickListener(this);
		btnRing.setOnClickListener(this);
		btnCallTimer.setOnClickListener(this);
		btnSpeak.setOnClickListener(this);

		return rootView;
	}

	@Override
	public void onActivityResult(int reqCode, int resultCode, Intent data) {
		super.onActivityResult(reqCode, resultCode, data);
		switch (reqCode) {
		case (PICK):
			if (resultCode == Activity.RESULT_OK) {
				Uri contactData = data.getData();
				Cursor c = getActivity().getContentResolver().query(
						contactData, null, null, null, null);
				if (c.moveToFirst()) {
					String id = c
							.getString(c
									.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

					String hasPhone = c
							.getString(c
									.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

					if (hasPhone.equalsIgnoreCase("1")) {
						Cursor phones = getActivity()
								.getContentResolver()
								.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
										null,
										ContactsContract.CommonDataKinds.Phone.CONTACT_ID
												+ " = " + id, null, null);
						phones.moveToFirst();
						String cNumber = phones
								.getString(phones
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						String nameContact = c
								.getString(c
										.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
						name = nameContact;
						etName.setText(name);
						etNumber.setText(cNumber);
						phoneId = fetchContactIdFromPhoneNumber(cNumber);
						Long temp = Long.valueOf(phoneId).longValue();
						Log.v("phoneId", phoneId);
						if (getPhotoUri(temp) != null)
							imageViewContact.setImageURI(getPhotoUri(temp));
					}
				}
			}
			break;
		case (RING):
			if (resultCode == Activity.RESULT_OK) {

				Uri uri = data
						.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
				if (uri != null) {
					ringTonePath = uri.toString();
					Log.v("*************", ringTonePath);
					Ringtone ring = RingtoneManager.getRingtone(getActivity(),
							uri);
					btnRing.setText(ring.getTitle(getActivity()));
				}

				break;
			}

		}

	}

	@SuppressLint("ShowToast")
	@Override
	public void onClick(View v) {
		button = (RadioButton) rootView.findViewById(group
				.getCheckedRadioButtonId());
		if (button.getText().equals("Incoming"))
			type = 2;
		else if (button.getText().equals("Missed"))
			type = 1;
		else if (button.getText().equals("Outgoing"))
			type = 3;
		Intent intent1 = new Intent(Intent.ACTION_PICK,
				ContactsContract.Contacts.CONTENT_URI);
		Intent intentRing = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);

		intentRing.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI,
				ringtone);
		intentRing.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI,
				ringtone);

		switch (v.getId()) {
		case R.id.btnSave:
			if (time > 0) {
				Log.v("fragment call", "btnSave");
				Log.v("call object", "name = " + etName.getText()
						+ " number = " + etNumber.getText() + "type = " + type
						+ " time = " + time + " vibrate = " + vibrate
						+ " duration = " + duration);
				CallReceiver cr = new CallReceiver();
				cr.setCall(getActivity(), etName.getText().toString(), etNumber
						.getText().toString(), ringTonePath, phoneId,
						time * 1000, type, vibrate, duration);
				Toast.makeText(getActivity(), "New call has been placed",
						Toast.LENGTH_LONG).show();
				getActivity().finish();
			} else if (time < 0) {
				CallLogHelper.insertPlaceholderCall(getActivity()
						.getContentResolver(), etName.getText().toString(),
						etNumber.getText().toString(), type, duration, date);
				Toast.makeText(getActivity(), "New call has been placed",
						Toast.LENGTH_SHORT).show();
				getActivity().finish();
			} else {
				Toast.makeText(getActivity(), "Please set time!",
						Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.btnContact:
			startActivityForResult(intent1, PICK);
			break;
		case R.id.btnRing:
			startActivityForResult(intentRing, 2);
			break;
		case R.id.btnTimer:
			onCreateDialog(TIME_DIALOG).show();
			break;
		case R.id.btnSpeak:
			onCreateDialog(DURATION_DIALOG).show();
			break;
		case R.id.tbPrivate:
			if (tbPrivate.isChecked()) {
				if (name != null)
					etName.setText(name);
				else
					etName.setText("");
				Log.v("tbPrivate", "not private");
			} else {
				etName.setText("Private Number");
				Log.v("tbPrivate", "private");
			}
			break;
		case R.id.tbVibrate:
			if (tbVibrate.isChecked()) {
				vibrate = false;
				Log.v("tbVibrate", "not vibrate");
			} else {
				vibrate = true;
				Log.v("tbVibrate", "vibrate");
			}
			break;
		}

	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG:
			hour = c.get(Calendar.HOUR_OF_DAY);
			minute = c.get(Calendar.MINUTE);
			Log.v("time", "hour = " + hour + " minute = " + minute);
			return new TimePickerDialog(getActivity(), timePickerListener,
					hour, minute + 1, true);
		case DURATION_DIALOG:
			LayoutInflater inflater = LayoutInflater.from(getActivity());
			View mView = inflater.inflate(R.layout.input_dialog, null);
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setView(mView);
			final EditText etDuration = (EditText) mView
					.findViewById(R.id.etDuration);
			builder.setCancelable(false)
					.setTitle("Talk time")
					.setPositiveButton("Set time",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub

									if (etDuration.getText().toString().trim()
											.length() != 0) {
										Log.v("set time", etDuration.getText()
												.toString());
										if (duration != 0)
											duration = Integer
													.parseInt(etDuration
															.getText()
															.toString());

										Log.v("set time", "" + duration);
										btnSpeak.setText(etDuration.getText()
												+ "s");
									} else
										dialog.dismiss();

								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();

								}
							});
			AlertDialog alertDialog = builder.create();
			return alertDialog;
		}
		return null;
	}

	private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int selectedHour,
				int selectedMinute) {
			hour = selectedHour;
			minute = selectedMinute;

			// set current time into textview
			btnCallTimer.setText(new StringBuilder().append(pad(hour))
					.append(":").append(pad(minute)));
			current_hour = c.get(Calendar.HOUR_OF_DAY);
			current_minute = c.get(Calendar.MINUTE);
			Log.v("time", "current = " + current_hour + ":" + current_minute
					+ " selected = " + hour + ":" + minute);
			if (current_hour == hour) {
				time = (minute - current_minute) * 60;
			} else {
				time = (((hour - current_hour) * 60 + minute) - current_minute) * 60;
			}
			Log.v("time", "" + time);
			if (time < 0) {
				c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1,
						c.get(Calendar.DAY_OF_MONTH), selectedHour,
						selectedMinute);
				date = c.getTimeInMillis();
				Log.v("date", "" + date);
			}
		}
	};

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	public String fetchContactIdFromPhoneNumber(String phoneNumber) {
		Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
				Uri.encode(phoneNumber));
		Cursor cursor = getActivity().getContentResolver().query(uri,
				new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
				null, null, null);

		String contactId = "";

		if (cursor.moveToFirst()) {
			do {
				contactId = cursor.getString(cursor
						.getColumnIndex(PhoneLookup._ID));
			} while (cursor.moveToNext());
		}

		return contactId;
	}

	public Uri getPhotoUri(long contactId) {
		ContentResolver contentResolver = getActivity().getContentResolver();

		try {
			Cursor cursor = contentResolver
					.query(ContactsContract.Data.CONTENT_URI,
							null,
							ContactsContract.Data.CONTACT_ID
									+ "="
									+ contactId
									+ " AND "

									+ ContactsContract.Data.MIMETYPE
									+ "='"
									+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
									+ "'", null, null);

			if (cursor != null) {
				if (!cursor.moveToFirst()) {
					return null; // no photo
				}
			} else {
				return null; // error in cursor process
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		Uri person = ContentUris.withAppendedId(
				ContactsContract.Contacts.CONTENT_URI, contactId);
		return Uri.withAppendedPath(person,
				ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
	}

}
